<template>
  <div id="address">
    <el-table
        :data="addresses"
        row-key="id"
        max-height="550"
        empty-text="还没有添加收货地址~">
      <el-table-column label="地址" prop="address"/>
      <el-table-column label="默认">
        <template v-slot="scope">
          <el-checkbox
              :value="scope.row.isDefault"
              :disabled="scope.row.isDefault"
              @change="setDefault(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="scope">
          <el-button @click="editAddress(scope.row)" type="text" size="small">编辑</el-button>
          <el-button @click="deleteItem(scope.row.id)" type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="收货地址" :visible.sync="showDialog">
      <el-form :model="form" :rules="rules" :show-message="true" ref="loginForm">
        <el-form-item label="收货地址" prop="address">
          <el-input v-model="form.address" />
        </el-form-item>
        <el-form-item label="默认地址">
          <el-checkbox v-model="form.isDefault" />
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-row type="flex" align="middle" justify="center">
      <el-col :span="4">
        <el-button type="primary" @click="addAddress">添加地址</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {mapState} from "vuex";
import axios from "axios";

export default {
  name: "AddressManage",
  computed: {
    ...mapState(['username'])
  },
  data() {
    return {
      addresses: [],
      form: {
        address: "",
        isDefault: false
      },
      showDialog: false,
      rules: {
        address: [
          {required: true, message: '地址为必填项！'}
        ]
      },
      update: false
    }
  },
  methods: {
    fetchAddresses() {
      axios.get('/api/address/show')
          .then(res => {
            this.addresses = res.data;
          });
    },
    deleteItem(id) {
      axios.post(`/api/address/del`, {id})
          .then(() => {
            this.$message({
              message: '删除成功！',
              type: "success"
            });
            this.fetchAddresses();
          })
          .catch(e => {
            if (e.response) {
              this.$message({
                message: `未知的服务器错误 代码${e.response.status}`,
                type: "error"
              });
            } else {
              this.$message({
                message: `未知的错误`,
                type: "error"
              });
            }
          })
    },
    setDefault(item) {
      // console.log(item);
      const body = {
        id: item.id,
        address: item.address,
        isDefault: true
      };
      axios.post('/api/address/edit', body)
          .then(() => {
            this.$message({
              message: '设置成功！',
              type: "success"
            });
            this.fetchAddresses();
          })
          .catch(e => {
            if (e.response) {
              this.$message({
                message: `未知的服务器错误 代码${e.response.status}`,
                type: "error"
              });
            } else {
              this.$message({
                message: `未知的错误`,
                type: "error"
              });
            }
          })
    },
    addAddress() {
      this.form = {
        address: "",
        isDefault: false
      }
      this.update = false
      this.showDialog = true
    },
    editAddress(item) {
      this.form = {
        id: item.id,
        address: item.address,
        isDefault: item.isDefault
      };
      this.update = true
      this.showDialog = true
    },
    cancelForm() {
      this.form = {
        address: "",
        isDefault: false
      }
      this.update = false
      this.showDialog = false
    },
    submitForm() {
      const update = this.update
      const form = this.form;
      if (!form.address) {
        return;
      }
      if (update) {
        axios.post('/api/address/edit', form)
            .then(() => {
              this.$message({
                message: '修改成功！',
                type: "success"
              });
              this.fetchAddresses();
            })
            .catch(e => {
              if (e.response) {
                this.$message({
                  message: `未知的服务器错误 代码${e.response.status}`,
                  type: "error"
                });
              } else {
                this.$message({
                  message: `未知的错误`,
                  type: "error"
                });
              }
            })
      } else {
        axios.post('/api/address/add', form)
            .then(() => {
              this.$message({
                message: '添加成功！',
                type: "success"
              });
              this.fetchAddresses();
            })
            .catch(e => {
              if (e.response) {
                this.$message({
                  message: `未知的服务器错误 代码${e.response.status}`,
                  type: "error"
                });
              } else {
                this.$message({
                  message: `未知的错误`,
                  type: "error"
                });
              }
            })
      }
      this.form = {
        address: "",
        isDefault: false
      };
      this.showDialog = false
    }
  },
  beforeMount() {
    if (!this.username) {
      this.$router.replace('/')  // 禁止未登录用户访问
    }
    this.fetchAddresses()
  }
}
</script>

<style scoped>

</style>